<template>
  <div class="avatar-upload">
    <div class="upload-container">
      <!-- 当前头像显示 -->
      <div class="current-avatar">
        <img 
          :src="currentAvatarUrl || defaultAvatar" 
          :alt="nickname || '用户头像'"
          class="avatar-image"
          @error="handleImageError"
        />
        <div class="avatar-overlay">
          <i class="icon-camera"></i>
          <span>更换头像</span>
        </div>
      </div>

      <!-- 文件选择输入 -->
      <input
        ref="fileInput"
        type="file"
        accept="image/*"
        style="display: none"
        @change="handleFileSelect"
      />

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <button 
          class="btn btn-primary"
          @click="selectFile"
          :disabled="uploading"
        >
          <i class="icon-upload"></i>
          {{ uploading ? '上传中...' : '选择头像' }}
        </button>
        
        <button 
          class="btn btn-secondary"
          @click="resetAvatar"
          :disabled="uploading"
          v-if="currentAvatarUrl"
        >
          <i class="icon-reset"></i>
          重置默认
        </button>
      </div>
    </div>

    <!-- 图片预览和裁剪模态框 -->
    <div v-if="showCropModal" class="crop-modal-overlay" @click="closeCropModal">
      <div class="crop-modal" @click.stop>
        <div class="crop-header">
          <h3>调整头像</h3>
          <button class="close-btn" @click="closeCropModal">×</button>
        </div>
        
        <div class="crop-container">
          <img 
            ref="cropImage"
            :src="previewImageUrl"
            class="crop-image"
          />
        </div>
        
        <div class="crop-controls">
          <div class="size-info">
            <span>建议尺寸：200x200像素</span>
            <span>文件大小：{{ formatFileSize(selectedFile?.size) }}</span>
          </div>
          
          <div class="crop-actions">
            <button class="btn btn-secondary" @click="closeCropModal">取消</button>
            <button 
              class="btn btn-primary" 
              @click="uploadAvatar"
              :disabled="uploading"
            >
              {{ uploading ? '上传中...' : '确认上传' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传进度 -->
    <div v-if="uploading" class="upload-progress">
      <div class="progress-bar">
        <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
      </div>
      <span class="progress-text">{{ uploadProgress }}%</span>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { uploadAvatar, updateUserAvatar, resetUserAvatar } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'AvatarUpload',
  props: {
    userId: {
      type: [String, Number],
      default: null
    },
    size: {
      type: String,
      default: 'large' // small, medium, large
    },
    editable: {
      type: Boolean,
      default: true
    }
  },
  emits: ['avatar-updated'],
  setup(props, { emit }) {
    const userStore = useUserStore()
    
    // 响应式数据
    const fileInput = ref(null)
    const cropImage = ref(null)
    const currentAvatarUrl = ref('')
    const nickname = ref('')
    const selectedFile = ref(null)
    const previewImageUrl = ref('')
    const showCropModal = ref(false)
    const uploading = ref(false)
    const uploadProgress = ref(0)
    
    // 默认头像
    const defaultAvatar = '/images/default-avatar.png'
    
    // 计算属性
    const isCurrentUser = computed(() => {
      return !props.userId || props.userId == userStore.userInfo?.id
    })
    
    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    // 加载用户头像信息
    const loadAvatarInfo = async () => {
      try {
        let response
        if (isCurrentUser.value) {
          response = await userStore.getCurrentUserAvatar()
        } else {
          response = await userStore.getUserAvatar(props.userId)
        }
        
        if (response.code === 200) {
          currentAvatarUrl.value = response.data.avatarUrl
          nickname.value = response.data.nickname
        }
      } catch (error) {
        console.error('加载头像信息失败:', error)
      }
    }
    
    // 选择文件
    const selectFile = () => {
      if (!props.editable || !isCurrentUser.value) {
        ElMessage.warning('无权限修改头像')
        return
      }
      fileInput.value?.click()
    }
    
    // 处理文件选择
    const handleFileSelect = (event) => {
      const file = event.target.files[0]
      if (!file) return
      
      // 验证文件类型
      const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp']
      if (!validTypes.includes(file.type)) {
        ElMessage.error('请选择有效的图片格式（jpg, jpeg, png, gif, bmp, webp）')
        return
      }
      
      // 验证文件大小 (5MB)
      if (file.size > 5 * 1024 * 1024) {
        ElMessage.error('头像文件大小不能超过5MB')
        return
      }
      
      selectedFile.value = file
      
      // 创建预览URL
      const reader = new FileReader()
      reader.onload = (e) => {
        previewImageUrl.value = e.target.result
        showCropModal.value = true
      }
      reader.readAsDataURL(file)
      
      // 清空input值
      event.target.value = ''
    }
    
    // 关闭裁剪模态框
    const closeCropModal = () => {
      showCropModal.value = false
      selectedFile.value = null
      previewImageUrl.value = ''
    }
    
    // 上传头像
    const uploadAvatar = async () => {
      if (!selectedFile.value) return
      
      uploading.value = true
      uploadProgress.value = 0
      
      try {
        const formData = new FormData()
        formData.append('file', selectedFile.value)
        
        // 模拟上传进度
        const progressInterval = setInterval(() => {
          uploadProgress.value += 10
          if (uploadProgress.value >= 90) {
            clearInterval(progressInterval)
          }
        }, 200)
        
        const response = await updateUserAvatar(formData)
        
        clearInterval(progressInterval)
        uploadProgress.value = 100
        
        if (response.code === 200) {
          currentAvatarUrl.value = response.data.avatarUrl
          
          // 更新用户store中的头像信息
          if (isCurrentUser.value) {
            userStore.updateUserInfo({
              avatar: response.data.avatarUrl
            })
          }
          
          ElMessage.success('头像更新成功')
          emit('avatar-updated', response.data.avatarUrl)
          closeCropModal()
        } else {
          throw new Error(response.message || '上传失败')
        }
      } catch (error) {
        console.error('上传头像失败:', error)
        ElMessage.error('上传头像失败: ' + error.message)
      } finally {
        uploading.value = false
        uploadProgress.value = 0
      }
    }
    
    // 重置头像
    const resetAvatar = async () => {
      try {
        await ElMessageBox.confirm('确定要重置为默认头像吗？', '确认重置', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await resetUserAvatar()
        
        if (response.code === 200) {
          currentAvatarUrl.value = response.data.avatarUrl
          
          // 更新用户store中的头像信息
          if (isCurrentUser.value) {
            userStore.updateUserInfo({
              avatar: response.data.avatarUrl
            })
          }
          
          ElMessage.success('头像已重置为默认头像')
          emit('avatar-updated', response.data.avatarUrl)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('重置头像失败:', error)
          ElMessage.error('重置头像失败')
        }
      }
    }
    
    // 处理图片加载错误
    const handleImageError = (event) => {
      event.target.src = defaultAvatar
    }
    
    // 组件挂载时加载头像信息
    onMounted(() => {
      loadAvatarInfo()
    })
    
    return {
      fileInput,
      cropImage,
      currentAvatarUrl,
      nickname,
      selectedFile,
      previewImageUrl,
      showCropModal,
      uploading,
      uploadProgress,
      defaultAvatar,
      isCurrentUser,
      formatFileSize,
      selectFile,
      handleFileSelect,
      closeCropModal,
      uploadAvatar,
      resetAvatar,
      handleImageError
    }
  }
}
</script>

<style scoped>
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.upload-container {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.current-avatar {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 3px solid #e0e0e0;
  transition: all 0.3s ease;
}

.current-avatar:hover {
  border-color: #1976d2;
}

.current-avatar:hover .avatar-overlay {
  opacity: 1;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  font-size: 12px;
}

.icon-camera::before {
  content: "📷";
  font-size: 20px;
  margin-bottom: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 5px;
}

.btn-primary {
  background: #1976d2;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #1565c0;
}

.btn-secondary {
  background: #f5f5f5;
  color: #666;
}

.btn-secondary:hover:not(:disabled) {
  background: #e0e0e0;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.icon-upload::before {
  content: "⬆️";
}

.icon-reset::before {
  content: "🔄";
}

/* 裁剪模态框样式 */
.crop-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.crop-modal {
  background: white;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 80vh;
  overflow: hidden;
}

.crop-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.crop-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.crop-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  max-height: 300px;
  overflow: hidden;
}

.crop-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8px;
}

.crop-controls {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.size-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 12px;
  color: #666;
}

.crop-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 上传进度样式 */
.upload-progress {
  width: 100%;
  max-width: 300px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar {
  flex: 1;
  height: 6px;
  background: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #1976d2;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 12px;
  color: #666;
  min-width: 35px;
}

/* 不同尺寸的头像 */
.avatar-upload.small .current-avatar {
  width: 60px;
  height: 60px;
}

.avatar-upload.medium .current-avatar {
  width: 80px;
  height: 80px;
}

.avatar-upload.large .current-avatar {
  width: 120px;
  height: 120px;
}
</style> 